package cn.iocoder.yudao.module.product.category.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.product.category.dal.dataobject.ProductCategoryDO;
import cn.iocoder.yudao.module.product.category.service.ProductCategoryService;
import cn.iocoder.yudao.module.product.category.vo.AppProductCategoryListReqVO;
import cn.iocoder.yudao.module.product.category.vo.AppProductCategoryRespVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.product.category.dal.dataobject.ProductCategoryDO.PARENT_ID_FIRST_LEVEL;

@Tag(name = "用户 APP - 产品分类")
@RestController
@RequestMapping("/product/category")
@Validated
public class AppProductCategoryController {

    @Resource
    private ProductCategoryService productCategoryService;

    @GetMapping("/list")
    @Operation(summary = "获得产品分类列表")
    @PermitAll
    public CommonResult<List<AppProductCategoryRespVO>> getProductCategoryList(@Valid AppProductCategoryListReqVO reqVO) {
        List<ProductCategoryDO> list;
        if (Boolean.TRUE.equals(reqVO.getAllChildren())) {
            // 明确指定查询所有下级分类
            list = productCategoryService.getEnableDescendentCategoryList(reqVO);
        } else {
            // 默认只查询顶级分类
            if (reqVO.getParentId() == null || reqVO.getParentId() < 0 || CollUtil.isEmpty(reqVO.getParentIds())) {
                reqVO.setParentId(PARENT_ID_FIRST_LEVEL);
            }
            list = productCategoryService.getEnableCategoryList(reqVO);
        }
        return success(BeanUtils.toBean(list, AppProductCategoryRespVO.class));
    }

    @GetMapping("/tree")
    @Operation(summary = "获得产品分类列表（树形）")
    @Parameter(name = "shopId", description = "店铺编号", required = true, example = "1")
    @PermitAll
    public CommonResult<List<Tree<Long>>> getProductCategoryTree(@RequestParam("shopId") Long shopId) {
        if (shopId == null || shopId <= 0) {
            return CommonResult.error(BAD_REQUEST);
        }
        AppProductCategoryListReqVO reqVO = new AppProductCategoryListReqVO();
        reqVO.setShopId(shopId);
        List<ProductCategoryDO> list = productCategoryService.getEnableDescendentCategoryList(reqVO);
        List<TreeNode<Long>> data = new ArrayList<>();
        for (ProductCategoryDO item : list) {
            TreeNode<Long> respVO = new TreeNode<>();
            respVO.setId(item.getId());
            respVO.setParentId(item.getParentId());
            respVO.setName(item.getName());
            respVO.setWeight(item.getSort());
            respVO.setExtra(MapUtil.<String, Object>builder()
                    .put("picUrl", StrUtil.emptyToDefault(item.getPicUrl(), ""))
                    .put("linkUrl", StrUtil.emptyToDefault(item.getLinkUrl(), ""))
                    .put("code", StrUtil.emptyToDefault(item.getCode(), ""))
                    .put("recommend", Boolean.TRUE.equals(item.getRecommend()))
                    .build());
            data.add(respVO);
        }
        return success(TreeUtil.build(data, PARENT_ID_FIRST_LEVEL));
    }

    @GetMapping("/list-by-ids")
    @Operation(summary = "获得产品分类列表(指定多个编号)")
    @Parameter(name = "ids", description = "产品分类编号数组", required = true, example = "1,2,3")
    @PermitAll
    public CommonResult<List<AppProductCategoryRespVO>> getProductCategoryList(@RequestParam("ids") Set<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return success(new ArrayList<>());
        }
        List<ProductCategoryDO> list = productCategoryService.getEnableCategoryList(ids);
        return success(BeanUtils.toBean(list, AppProductCategoryRespVO.class));
    }

}
